package ltd.dujiabao.zookeeper.watcher;

import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.concurrent.CountDownLatch;

/**
 * @author : DuJiabao
 * @Project : zookeeper
 * @Time : 2021/5/2 21:46
 * @Desc :
 */
public class ZKCommonWatcher implements Watcher {
  private CountDownLatch countDownLatch = null;
  private static final Logger log = Logger.getLogger(ZKConnectionWatcher.class);

  public ZKCommonWatcher() {
  }

  public ZKCommonWatcher(CountDownLatch countDownLatch) {
    this.countDownLatch = countDownLatch;
  }

  @Override
  public void process(WatchedEvent watchedEvent) {
    switch (watchedEvent.getType()) {
      case NodeCreated:
        log.info("节点创建了");
        break;
      case NodeDataChanged:
        log.info("节点数据被修改了");
        break;
      case NodeDeleted:
        log.info("节点被删除了");
        break;
      case None: {
        Event.KeeperState state = watchedEvent.getState();
        log.info(state);
        if (this.countDownLatch != null && state == Event.KeeperState.SyncConnected)
          this.countDownLatch.countDown();
        break;
      }
    }
  }

  public void setCountDownLatch(CountDownLatch countDownLatch) {
    this.countDownLatch = countDownLatch;
  }
}
